package com.chenyue.cm.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.common.constant.DomainConfig;
import com.chenyue.cm.common.constant.ErrorCode;
import com.chenyue.cm.common.utils.StringUtils;
import com.chenyue.cm.exception.SysRuntimeException;
import com.chenyue.cm.tecentCloud.LiveRecordAddressUtils;
import com.chenyue.cm.user.dao.JdVerifyMapper;
import com.chenyue.cm.user.domain.JdVerify;
import com.chenyue.cm.user.service.JdVerifyService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.BizLicenseOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.BizLicenseOCRResponse;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;


/**
 * @author LBX
 */
@Service(value = "JdVerifyService")
public class JdVerifyServiceImpl extends BaseServiceImpl<JdVerify> implements JdVerifyService {

    private final JdVerifyMapper verifyMapper;

    public JdVerifyServiceImpl(@Qualifier("jdVerifyMapper") JdVerifyMapper verifyMapper) {
        this.verifyMapper = verifyMapper;
    }

    @Override
    @Resource(name = "jdVerifyMapper")
    public void setBaseMapper(LcBaseMapper<JdVerify, Serializable> baseMapper) {
        this.baseMapper = baseMapper;
    }

    /**
     * 身份证是否已使用
     *
     * @param cardNumber 身份证
     * @return 错误信息
     */
    @Override
    public String isBindCard(String cardNumber) {
        JdVerify verify = verifyMapper.selectOne(new QueryWrapper<JdVerify>().lambda().eq(JdVerify::getCardNumber, cardNumber).last(" limit 1 "));
        return verify == null ? "" : "该证件号已经被使用";
    }

    /**
     * 根据用户id获取实名信息
     *
     * @param id 用户id
     * @return 实名信息
     */
    @Override
    public JdVerify getVerifyInfo(Integer id) {
        return verifyMapper.selectOne(new QueryWrapper<JdVerify>().lambda().eq(JdVerify::getUserId, id).last(" limit 1 "));
    }

    /**
     * 保存实名信息 生成附带信息
     *
     * @param verify 实名信息
     *               身份证号 证件类型 身份证正面 身份证背面 营业执照 正反面+编号
     */
    @Override
    public void saveVerify(JdVerify verify) {
        final JdVerify verifyInfo = getVerifyInfo(verify.getUserId());

        if (StringUtils.isNotBlank(verify.getBusPositive())) {
            verify = getBusInfo(verify);
            final JdVerify old = verifyMapper.selectOne(
                    new LambdaQueryWrapper<JdVerify>()
                            .eq(JdVerify::getBusNumber, verify.getBusNumber())
                            .last(" limit 1")
            );
            if (old != null) {
                if (!old.getUserId().equals(verify.getUserId())) {
                    throw new SysRuntimeException("该执照已被使用");
                }
            }
        } else {
            verify = getInfo(verify);
            final JdVerify old = verifyMapper.selectOne(
                    new LambdaQueryWrapper<JdVerify>()
                            .eq(JdVerify::getCardNumber, verify.getCardNumber())
                            .last(" limit 1")
            );
            if (old != null) {
                if (!old.getUserId().equals(verify.getUserId())) {
                    throw new SysRuntimeException("该身份证已被使用");
                }
            }
        }
        verify.setState(1);
        if (verifyInfo == null) {
            int insert = verifyMapper.insert(verify);
            if (insert == 0) {
                throw new SysRuntimeException(ErrorCode.INSERT_ERROR.getMsg());
            }
        } else {
            verify.setId(verifyInfo.getId());
            int insert = verifyMapper.updateById(verify);
            if (insert == 0) {
                throw new SysRuntimeException(ErrorCode.UPDATE_ERROR.getMsg());
            }
        }
    }

    @Override
    public void checkVerify(Integer userId, Integer state, String remark) {
        JdVerify verifyInfo = getVerifyInfo(userId);
        verifyInfo.setState(state);
        verifyInfo.setRemark(remark);
        final int update = verifyMapper.updateById(verifyInfo);
        if (update == 0) {
            throw new SysRuntimeException(ErrorCode.UPDATE_ERROR.getMsg());
        }
    }

    /**
     * @param verify 身份证正反面
     * @return 实名信息
     */
    @Override
    public JdVerify getInfo(JdVerify verify) {
        final OcrClient ocrClient = new OcrClient(LiveRecordAddressUtils.getCredential(), "ap-beijing");
        IDCardOCRRequest param = new IDCardOCRRequest();
        param.setCardSide("FRONT");
        param.setImageUrl(DomainConfig.LOCALHOST + verify.getCertPositive());
        System.err.println(DomainConfig.LOCALHOST + verify.getCertPositive());
        try {
            final IDCardOCRResponse ocrResponse = ocrClient.IDCardOCR(param);
            verify.setCardNumber(ocrResponse.getIdNum());
            verify.setCertType(1);
            verify.setNativePlace(ocrResponse.getAddress());
            verify.setName(ocrResponse.getName());
        } catch (TencentCloudSDKException e) {
            final String s = e.getMessage().split("-")[1];
            System.err.println(s);
            throw new SysRuntimeException(s);
        }
        return verify;
    }

    /**
     * 根据营业执照获取编号
     *
     * @param verifyInfo 营业执照
     * @return 编号
     */
    @Override
    public JdVerify getBusInfo(JdVerify verifyInfo) {
        final OcrClient ocrClient = new OcrClient(LiveRecordAddressUtils.getCredential(), "ap-beijing");
        BizLicenseOCRRequest param = new BizLicenseOCRRequest();
        param.setImageUrl(DomainConfig.LOCALHOST + verifyInfo.getBusPositive());
        try {
            final BizLicenseOCRResponse response = ocrClient.BizLicenseOCR(param);
            verifyInfo.setBusNumber(response.getRegNum());
            if (StringUtils.isEmpty(verifyInfo.getName())) {
                verifyInfo.setName(response.getPerson());
            }
            if (StringUtils.isEmpty(verifyInfo.getNativePlace())) {
                verifyInfo.setNativePlace(response.getAddress());
            }
        } catch (TencentCloudSDKException e) {
            final String s = e.getMessage().split("-")[1];
            System.err.println(s);
            throw new SysRuntimeException(s);
        }
        return verifyInfo;
    }
}
